package org.dromara.signIn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.system.domain.SysUser;
import org.dromara.system.mapper.SysUserMapper;
import org.springframework.stereotype.Service;
import org.dromara.signIn.domain.bo.SignInRecordBo;
import org.dromara.signIn.domain.vo.SignInRecordVo;
import org.dromara.signIn.domain.SignInRecord;
import org.dromara.signIn.mapper.SignInRecordMapper;
import org.dromara.signIn.service.ISignInRecordService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 签到记录Service业务层处理
 *
 * @author Lion Li
 * @date 2025-09-25
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SignInRecordServiceImpl implements ISignInRecordService {

    private final SignInRecordMapper baseMapper;
    private final SysUserMapper userMapper;

    /**
     * 查询签到记录
     *
     * @param id 主键
     * @return 签到记录
     */
    @Override
    public SignInRecordVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询签到记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 签到记录分页列表
     */
    @Override
    public TableDataInfo<SignInRecordVo> queryPageList(SignInRecordBo bo, PageQuery pageQuery) {
        if (bo.getUsername() == null) {
            LambdaQueryWrapper<SignInRecord> lqw = buildQueryWrapper(bo);
            Page<SignInRecordVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
            return TableDataInfo.build(result);
        }
        // 模糊查询用户名称
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.like("user_name",bo.getUsername());

        // 处理用户id
        List<String> sysUserIds = userMapper.selectList(sysUserQueryWrapper)
            .stream()
            .map(sysUser->sysUser.getUserId().toString())
            .toList();
        log.info("查询到{}个用户,sysUserId:{}", sysUserIds.size(), sysUserIds);

        if (sysUserIds.isEmpty()) {
            return TableDataInfo.build(new Page<>());
//            throw new RuntimeException("没有找到对应用户");
        }

        // 处理分页
        Page<Object> page = pageQuery.build();

        // 查询用户id对应的签到记录
        Page<SignInRecordVo> result = baseMapper.selectRecordsByUserIds(page, sysUserIds);
        log.info("查询到{}条签到记录,result:{}", result.getTotal(), result);
        return TableDataInfo.build(result);
    }

    @Override
    public List<SignInRecordVo> counterToday(Long userId, Long taskId) {
        return baseMapper.findTodayRecords(userId, taskId);
    }

    @Override
    public SignInRecordVo findLastSignInRecord(SignInRecordBo bo) {
        List<SignInRecordVo> records = baseMapper.findTodayRecords(bo.getUserId(), bo.getTaskId());
        return records.get(records.size()-1);
    }

    /**
     * 查询符合条件的签到记录列表
     *
     * @param bo 查询条件
     * @return 签到记录列表
     */
    @Override
    public List<SignInRecordVo> queryList(SignInRecordBo bo) {
        LambdaQueryWrapper<SignInRecord> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SignInRecord> buildQueryWrapper(SignInRecordBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SignInRecord> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(SignInRecord::getId);
        lqw.eq(bo.getUserId() != null, SignInRecord::getUserId, bo.getUserId());
        lqw.eq(bo.getRelatedSignId() != null, SignInRecord::getRelatedSignId, bo.getRelatedSignId());
        return lqw;
    }

    /**
     * 新增签到记录
     *
     * @param bo 签到记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SignInRecordBo bo) {
        SignInRecord add = MapstructUtils.convert(bo, SignInRecord.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改签到记录
     *
     * @param bo 签到记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SignInRecordBo bo) {
        SignInRecord update = MapstructUtils.convert(bo, SignInRecord.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SignInRecord entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除签到记录信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
